package com.x.chalk.service.impl;

import com.x.chalk.dao.MoodDao;
import com.x.chalk.dto.MoodPageDto;
import com.x.chalk.entity.Browse;
import com.x.chalk.entity.Mood;
import com.x.chalk.service.intf.BrowseService;
import com.x.chalk.service.intf.MoodService;
import com.x.chalk.util.BaiduCensorUtil;
import com.x.chalk.vo.PageVo;
import com.x.chalk.vo.R;
import com.x.chalk.vo.parms.PageParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;


/**
 * @Author FSir
 * @create 2022/10/4 16:18
 */
@Service
public class MoodServiceImpl implements MoodService {
    @Autowired
    private MoodDao moodDao;
    @Autowired
    private BrowseService browseService;

    @Override
    public R add(String info, String token) {
        /**
         * 参数校验
         * 文本审核
         */
        if (StringUtils.hasLength(info)) {
            boolean flag = BaiduCensorUtil.textCensor(info);
            Mood mood = new Mood(Long.parseLong(token),info);
            if (flag){
                moodDao.insert(mood);
            }else {
                mood.setState(2);//审核未通过
                moodDao.insert(mood);
            }
            return R.ok();
        }
        return R.fail();
    }

    @Override
    public R queryPage(PageParams pageParams) {
        if (Objects.nonNull(pageParams)){
            long total=moodDao.selectCount();
            long pages=total%pageParams.getPageSize()==0?total/pageParams.getPageSize():total/pageParams.getPageSize()+1;
            return R.ok(new PageVo<MoodPageDto>(total,pages,moodDao.moodpage((pageParams.getPage()-1)*pageParams.getPageSize(),pageParams.getPageSize())));
        }
        return R.fail();
    }

    @Override
    @Transactional
    public R queryOne(int id) {
        /**
         * 查看当前动态
         * 判断是否已经浏览过
         * 增加浏览量
         */
        if (id>0){
            MoodPageDto mood = moodDao.findMoodAndUser(id);
            Browse browse = browseService.queryOne(mood.getUid(), mood.getId());
            if (browse==null){
                browseService.add(mood.getUid(),mood.getId());
            }
            return R.ok(mood);
        }
        return R.fail();
    }

    @Override
    public R queryMy(String token) {
        long uid = Long.parseLong(token);
       List<MoodPageDto> moodPageDtoList= moodDao.findMyMood(uid);
        return R.ok(moodPageDtoList);
    }

    @Override
    public int updateLikeNum(int num,Long id) {
        return moodDao.updateLikeNum(num,id);
    }
}
